import urllib
import urllib.parse
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
file_api_router = APIRouter()
_active = True  # 激活状态

from fastapi.responses import FileResponse

async def file_iterator(file_path: str, chunk_size: int = 8192):
    """异步分块读取文件"""
    with open(file_path, "rb") as file:
        while chunk := file.read(chunk_size):
            yield chunk

@file_api_router.get("/download/collection/{file_path}/{file_name}")
async def download_small_file(file_path: str, file_name: str):
    print("filename")
    file_path = f"/data/ais/hkpc/sfc/download/{file_name}"
    encoded_file_name = urllib.parse.quote(file_name)  # URL-encode the filename
    return StreamingResponse(
        file_iterator(file_path),
        media_type="application/octet-stream",
        headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_file_name}"}
    )